/*
 * Copyright (c) 2024 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import { GlobMatch } from '../utils/common/GlobMatch';

export interface RuleConfig {
    files: GlobMatch;
    ignore: GlobMatch;
    rules: object;
    extRules: object;
    extRuleSet: object[];
    ruleSet: string[];
    overrides: RuleConfig[];
}

export interface RuleConfigOptions {
    files: string[],
    ignore: string[],
    rules: {
        [key: string]: number
    }
    ruleSet: string[]
    overrides: [],
    extRuleSet: []
}

export function parseRuleConfig(config: any): RuleConfig {
    const ruleConfig: RuleConfig = {
        files: new GlobMatch(['**/*.ets']),
        ignore: new GlobMatch([]),
        rules: {},
        extRules: {},
        extRuleSet: [],
        ruleSet: [],
        overrides: []
    };

    if (config.files && config.files.length > 0) {
        ruleConfig.files = new GlobMatch(config.files);
    } else {
        ruleConfig.files = new GlobMatch(['**/*.ets']);
    }
    if (config.ignore) {
        if (config.ignore.length > 0) {
            ruleConfig.ignore = new GlobMatch(config.ignore);
        }
    } else if (config.excluded && config.excluded.length > 0) {
        ruleConfig.ignore = new GlobMatch(config.excluded);
    }
    ruleConfig.rules = config.rules ?? {};
    ruleConfig.extRules = config.extRules ?? {};
    ruleConfig.extRuleSet = config.extRuleSet ?? [];
    ruleConfig.ruleSet = config.ruleSet ?? [];

    if (config.overrides) {
        let overrides: RuleConfig[] = [];
        let overRuleConfigs = config.overrides;
        overRuleConfigs.forEach((overRuleConfig: any) => {
            overrides.push(parseRuleConfig(overRuleConfig));
        });
        ruleConfig.overrides = overrides;
    } else {
        ruleConfig.overrides = [];
    }

    return ruleConfig;
}

export const DEFAULT_RULE_CONFIG_OPTIONS: RuleConfigOptions = {
    files: [
        "**/*.ets",
        "**/*.ts"
    ],
    ignore: [
        "**/ohosTest/**/*",
        "**/node_modules/**/*",
        "**/build/**/*",
        "**/hvigorfile/**/*",
        "**/oh_modules/**/*",
        "**/.preview/**/*"
    ],
    rules: {
        "@performance/foreach-args-check": 3
    },
    ruleSet: [
        "plugin:@ArkTS-eslint/all",
        "plugin:@performance/all",
        "plugin:@correctness/all"
    ],
    overrides: [],
    extRuleSet: []
};